package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"post-mania/cache"
	"post-mania/models"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")

	if title == "" || content == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}

	post := models.Post{
		Title:   title,
		Content: content,
	}

	err := models.DB.Create(&post).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}

	redis_key := "post_id" + strconv.Itoa(int(post.ID))
	models.DB.Where("id=?", post.ID).First(&post).Debug()
	jsonData, _ := json.Marshal(post)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})

}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var post models.Post
	err := models.DB.Where("id=?", id).First(&post).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": post,
	})
	return
}

func Del(c *gin.Context) {
	id := c.Query("id")
	err := models.DB.Where("id=?", id).Delete(&models.Post{}).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}
	redis_key := "post_id" + id
	cache.Rdb.Del(cache.Ctx, redis_key)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}

func List(c *gin.Context) {
	var post []models.Post

	redis_key := "post_list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Find(&post).Debug()
		jsonData, _ := json.Marshal(post)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &post)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": post,
	})
	return
}
